package com.toprs.business.service

import cn.afterturn.easypoi.excel.ExcelExportUtil
import cn.afterturn.easypoi.excel.entity.TemplateExportParams
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.toprs.business.entity.ApplicationBase
import com.toprs.business.entity.StatisticEntity
import com.toprs.business.mapper.ApplicationBaseMapper
import com.toprs.business.mapper.ApplicationStatisticMapper
import com.toprs.business.mapper.statisticByDept
import com.toprs.business.mapper.statisticByMonth
import com.toprs.business.vo.StatisticVO
import jakarta.servlet.http.HttpServletResponse
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
import java.math.BigDecimal


@Service
class StatisticService(val applicationStatisticMapper: ApplicationStatisticMapper) {


    private fun addSum(list: List<StatisticEntity>): List<StatisticEntity> {

        val list0 = list.toMutableList()

        val sum =
            StatisticEntity(BigDecimal(0), BigDecimal(0), BigDecimal(0), BigDecimal(0), BigDecimal(0), BigDecimal(0))
        sum.deptName = "合计"
        sum.month = "合计"
        for (it in list0) {
            sum.cast = sum.cast?.plus(it.cast!!)
            sum.bxAmount = sum.bxAmount?.plus(it.bxAmount!!)
            sum.stayPrice = sum.stayPrice?.plus(it.stayPrice!!)
            sum.winePrice = sum.winePrice?.plus(it.winePrice!!)
            sum.otherPrice = sum.otherPrice?.plus(it.otherPrice!!)
            sum.catePrice = sum.catePrice?.plus(it.catePrice!!)
        }
        list0.add(sum)
        return list0.toList()
    }


    fun statisticByDept(statisticVO: StatisticVO): List<StatisticEntity> {

        val list = applicationStatisticMapper.statisticByDept(statisticVO)
        return addSum(list)
    }

    fun statisticByMonth(statisticVO: StatisticVO): List<StatisticEntity> {

        val list = applicationStatisticMapper.statisticByMonth(statisticVO)
        return addSum(list)
    }

    fun exportExcel(statisticVO: StatisticVO, type: Int, response: HttpServletResponse) {

        val list = if (type == 0) statisticByDept(statisticVO) else statisticByMonth(statisticVO)

        val map = hashMapOf("maplist" to list)


        val url = if (type == 0) "statistic_dept.xlsx" else "statistic_month.xlsx"


        val inputStream = ClassPathResource(url).inputStream
        val params = TemplateExportParams(inputStream)

        response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        response.characterEncoding = "UTF-8"

        val workbook = ExcelExportUtil.exportExcel(params, map as Map<String, Any>?)
        val ops = response.outputStream
        workbook.write(ops)
        ops.flush()
        ops.close()
//        workbook.close()

    }
}